package com.lzxuni.common.exception;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lzxuni.common.utils.R;
import com.lzxuni.config.MailConfig;
import com.lzxuni.modules.organization.entity.User;
import com.lzxuni.modules.shiro.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;

import java.util.Map;

/**
 * 〈一句话功能简述〉<br>
 *
 * @author:孙志强
 * @create:2018-06-19 14:19
 * @Modified BY:
 **/
@Component
public class LzxErrorAttributes extends DefaultErrorAttributes {
	@Autowired
	private MailConfig mailConfig;


	public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
		Map<String, Object> map = super.getErrorAttributes(webRequest, includeStackTrace);
		//如果有自定义需要携带的数据
		R r = (R)webRequest.getAttribute("r", 0);
		if(r!=null){
			map.putAll(r);
		}
		try {
			sendMail(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}


	private void sendMail(Map map) {
		String s = JSON.toJSONString(map, SerializerFeature.WriteDateUseDateFormat);
		User user = ShiroUtils.getUser();
		new Thread(() -> {
			mailConfig.sendMail("金融平台监控信息:操作用户："+ user.getRealName()+"", s);
		}).start();
	}
}
